<template>
  <view class="ad-statistics-container">
    <!-- 统计概览卡片 -->
    <view class="overview-cards">
      <view class="stat-card">
        <view class="stat-icon">👁️</view>
        <view class="stat-content">
          <view class="stat-value">{{ formatNumber(overviewData.totalViews) }}</view>
          <view class="stat-label">总观看次数</view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon">✅</view>
        <view class="stat-content">
          <view class="stat-value">{{ formatNumber(overviewData.completedViews) }}</view>
          <view class="stat-label">完成观看</view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon">👥</view>
        <view class="stat-content">
          <view class="stat-value">{{ formatNumber(overviewData.uniqueUsers) }}</view>
          <view class="stat-label">独立用户</view>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-icon">🎁</view>
        <view class="stat-content">
          <view class="stat-value">{{ formatNumber(overviewData.totalRewards) }}</view>
          <view class="stat-label">总奖励积分</view>
        </view>
      </view>
    </view>
    
    <!-- 关键指标 -->
    <view class="metrics-section">
      <view class="section-title">关键指标</view>
      <view class="metrics-grid">
        <view class="metric-item">
          <view class="metric-label">完成率</view>
          <view class="metric-value">{{ overviewData.completionRate }}%</view>
          <view class="metric-bar">
            <view 
              class="metric-fill" 
              :style="{ width: overviewData.completionRate + '%' }"
            ></view>
          </view>
        </view>
        
        <view class="metric-item">
          <view class="metric-label">平均观看时长</view>
          <view class="metric-value">{{ formatDuration(overviewData.avgViewDuration) }}</view>
        </view>
        
        <view class="metric-item">
          <view class="metric-label">人均观看次数</view>
          <view class="metric-value">{{ overviewData.avgViewsPerUser }}</view>
        </view>
        
        <view class="metric-item">
          <view class="metric-label">平均奖励/次</view>
          <view class="metric-value">{{ overviewData.avgRewardPerView }}</view>
        </view>
      </view>
    </view>
    
    <!-- 趋势图表 -->
    <view class="chart-section" v-if="showCharts">
      <view class="section-title">观看趋势</view>
      <view class="chart-container">
        <canvas 
          canvas-id="trendChart" 
          class="chart-canvas"
          @touchstart="handleChartTouch"
          @touchmove="handleChartTouch"
          @touchend="handleChartTouch"
        ></canvas>
      </view>
    </view>
    
    <!-- 平台分布 -->
    <view class="platform-section">
      <view class="section-title">平台分布</view>
      <view class="platform-list">
        <view 
          v-for="(platform, index) in platformData" 
          :key="index"
          class="platform-item"
        >
          <view class="platform-info">
            <view class="platform-name">{{ getPlatformName(platform.platform) }}</view>
            <view class="platform-stats">
              <text>观看: {{ formatNumber(platform.views) }}</text>
              <text>完成率: {{ platform.completionRate }}%</text>
            </view>
          </view>
          <view class="platform-chart">
            <view 
              class="platform-bar"
              :style="{ width: (platform.views / maxPlatformViews * 100) + '%' }"
            ></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 广告类型分布 -->
    <view class="ad-type-section">
      <view class="section-title">广告类型分布</view>
      <view class="ad-type-list">
        <view 
          v-for="(adType, index) in adTypeData" 
          :key="index"
          class="ad-type-item"
        >
          <view class="ad-type-info">
            <view class="ad-type-name">{{ getAdTypeName(adType.adType) }}</view>
            <view class="ad-type-stats">
              <text>观看: {{ formatNumber(adType.views) }}</text>
              <text>奖励: {{ formatNumber(adType.totalRewards) }}</text>
            </view>
          </view>
          <view class="ad-type-chart">
            <view 
              class="ad-type-bar"
              :style="{ width: (adType.views / maxAdTypeViews * 100) + '%' }"
            ></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 收益分析 -->
    <view class="revenue-section">
      <view class="section-title">收益分析</view>
      <view class="revenue-cards">
        <view class="revenue-card">
          <view class="revenue-label">总奖励积分</view>
          <view class="revenue-value">{{ formatNumber(revenueData.totalRewards) }}</view>
        </view>
        <view class="revenue-card">
          <view class="revenue-label">预估收入</view>
          <view class="revenue-value">¥{{ formatNumber(revenueData.estimatedRevenue) }}</view>
        </view>
      </view>
      
      <view class="revenue-breakdown">
        <view class="breakdown-title">按广告类型收益分布</view>
        <view 
          v-for="(item, index) in revenueData.revenueByAdType" 
          :key="index"
          class="breakdown-item"
        >
          <view class="breakdown-info">
            <text class="breakdown-name">{{ getAdTypeName(item.adType) }}</text>
            <text class="breakdown-value">{{ formatNumber(item.rewards) }} 积分</text>
          </view>
          <view class="breakdown-bar">
            <view 
              class="breakdown-fill"
              :style="{ width: (item.rewards / revenueData.totalRewards * 100) + '%' }"
            ></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 刷新按钮 -->
    <view class="refresh-section">
      <button 
        class="refresh-btn" 
        @click="refreshData"
        :disabled="isLoading"
      >
        <text v-if="isLoading">刷新中...</text>
        <text v-else>刷新数据</text>
      </button>
    </view>
  </view>
</template>

<script>
import { getAdOverview, getAdTrend, getAdPlatformStats, getAdTypeStats, getAdRevenue } from '@/api/ads.js'

export default {
  name: 'AdStatistics',
  props: {
    dateRange: {
      type: Object,
      default: () => ({
        startDate: null,
        endDate: null
      })
    },
    showCharts: {
      type: Boolean,
      default: true
    }
  },
  
  data() {
    return {
      isLoading: false,
      overviewData: {
        totalViews: 0,
        completedViews: 0,
        uniqueUsers: 0,
        totalRewards: 0,
        completionRate: 0,
        avgViewDuration: 0,
        avgViewsPerUser: 0,
        avgRewardPerView: 0
      },
      trendData: [],
      platformData: [],
      adTypeData: [],
      revenueData: {
        totalRewards: 0,
        estimatedRevenue: 0,
        revenueByAdType: []
      },
      maxPlatformViews: 1,
      maxAdTypeViews: 1
    }
  },
  
  mounted() {
    this.loadStatistics()
  },
  
  watch: {
    dateRange: {
      handler() {
        this.loadStatistics()
      },
      deep: true
    }
  },
  
  methods: {
    /**
     * 加载统计数据
     */
    async loadStatistics() {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        const filters = {
          startDate: this.dateRange.startDate,
          endDate: this.dateRange.endDate
        }
        
        // 并行加载所有统计数据
        const [
          overviewResult,
          trendResult,
          platformResult,
          adTypeResult,
          revenueResult
        ] = await Promise.all([
          getAdOverview(filters),
          getAdTrend(filters),
          getAdPlatformStats(filters),
          getAdTypeStats(filters),
          getAdRevenue(filters)
        ])
        
        this.overviewData = overviewResult.data
        this.trendData = trendResult.data
        this.platformData = platformResult.data
        this.adTypeData = adTypeResult.data
        this.revenueData = revenueResult.data
        
        // 计算最大值用于图表显示
        this.maxPlatformViews = Math.max(...this.platformData.map(item => item.views), 1)
        this.maxAdTypeViews = Math.max(...this.adTypeData.map(item => item.views), 1)
        
        // 绘制趋势图表
        if (this.showCharts) {
          this.$nextTick(() => {
            this.drawTrendChart()
          })
        }
        
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.showError('加载统计数据失败')
      } finally {
        this.isLoading = false
      }
    },
    
    /**
     * 刷新数据
     */
    async refreshData() {
      await this.loadStatistics()
      this.showSuccess('数据刷新成功')
    },
    
    /**
     * 绘制趋势图表
     */
    drawTrendChart() {
      // #ifdef H5
      // H5环境下可以使用Chart.js等图表库
      // 这里提供一个简化的实现
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序环境下使用canvas绘制
      const ctx = uni.createCanvasContext('trendChart', this)
      
      if (!this.trendData || this.trendData.length === 0) {
        return
      }
      
      const canvasWidth = 300
      const canvasHeight = 200
      const padding = 40
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制坐标轴
      ctx.setStrokeStyle('#e0e0e0')
      ctx.setLineWidth(1)
      
      // X轴
      ctx.beginPath()
      ctx.moveTo(padding, canvasHeight - padding)
      ctx.lineTo(canvasWidth - padding, canvasHeight - padding)
      ctx.stroke()
      
      // Y轴
      ctx.beginPath()
      ctx.moveTo(padding, padding)
      ctx.lineTo(padding, canvasHeight - padding)
      ctx.stroke()
      
      // 绘制数据线
      if (this.trendData.length > 1) {
        const maxViews = Math.max(...this.trendData.map(item => item.views))
        const stepX = chartWidth / (this.trendData.length - 1)
        
        ctx.setStrokeStyle('#667eea')
        ctx.setLineWidth(2)
        ctx.beginPath()
        
        this.trendData.forEach((item, index) => {
          const x = padding + index * stepX
          const y = canvasHeight - padding - (item.views / maxViews) * chartHeight
          
          if (index === 0) {
            ctx.moveTo(x, y)
          } else {
            ctx.lineTo(x, y)
          }
        })
        
        ctx.stroke()
      }
      
      ctx.draw()
      // #endif
    },
    
    /**
     * 处理图表触摸事件
     */
    handleChartTouch(e) {
      // 图表交互逻辑
      console.log('图表触摸事件:', e)
    },
    
    /**
     * 格式化数字
     */
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k'
      }
      return num.toString()
    },
    
    /**
     * 格式化时长
     */
    formatDuration(seconds) {
      if (seconds >= 60) {
        const minutes = Math.floor(seconds / 60)
        const remainingSeconds = Math.floor(seconds % 60)
        return `${minutes}分${remainingSeconds}秒`
      }
      return `${Math.floor(seconds)}秒`
    },
    
    /**
     * 获取平台名称
     */
    getPlatformName(platform) {
      const platformNames = {
        'miniprogram': '小程序',
        'h5': 'H5',
        'app': 'APP'
      }
      return platformNames[platform] || platform
    },
    
    /**
     * 获取广告类型名称
     */
    getAdTypeName(adType) {
      const adTypeNames = {
        'video': '视频广告',
        'banner': 'Banner广告',
        'interstitial': '插屏广告',
        'native': '原生广告'
      }
      return adTypeNames[adType] || adType
    },
    
    /**
     * 显示成功提示
     */
    showSuccess(message) {
      if (typeof uni !== 'undefined' && uni.showToast) {
        uni.showToast({
          title: message,
          icon: 'success'
        })
      }
    },
    
    /**
     * 显示错误提示
     */
    showError(message) {
      if (typeof uni !== 'undefined' && uni.showToast) {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.ad-statistics-container {
  padding: 20rpx;
  background: #f5f5f5;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-card {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.metrics-section,
.chart-section,
.platform-section,
.ad-type-section,
.revenue-section {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.metric-item {
  text-align: center;
}

.metric-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.metric-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.metric-bar {
  height: 6rpx;
  background: #f0f0f0;
  border-radius: 3rpx;
  overflow: hidden;
}

.metric-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

.chart-container {
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-canvas {
  width: 100%;
  height: 100%;
}

.platform-list,
.ad-type-list {
  space-y: 16rpx;
}

.platform-item,
.ad-type-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.platform-info,
.ad-type-info {
  flex: 1;
  margin-right: 20rpx;
}

.platform-name,
.ad-type-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 4rpx;
}

.platform-stats,
.ad-type-stats {
  font-size: 24rpx;
  color: #666;
  
  text {
    margin-right: 16rpx;
  }
}

.platform-chart,
.ad-type-chart {
  width: 120rpx;
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.platform-bar,
.ad-type-bar {
  height: 100%;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.revenue-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 24rpx;
}

.revenue-card {
  text-align: center;
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 12rpx;
  color: white;
}

.revenue-label {
  font-size: 24rpx;
  opacity: 0.9;
  margin-bottom: 8rpx;
}

.revenue-value {
  font-size: 32rpx;
  font-weight: bold;
}

.revenue-breakdown {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.breakdown-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.breakdown-item {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.breakdown-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 20rpx;
}

.breakdown-name {
  font-size: 26rpx;
  color: #333;
}

.breakdown-value {
  font-size: 24rpx;
  color: #666;
}

.breakdown-bar {
  width: 100rpx;
  height: 6rpx;
  background: #f0f0f0;
  border-radius: 3rpx;
  overflow: hidden;
}

.breakdown-fill {
  height: 100%;
  background: linear-gradient(90deg, #52c41a, #73d13d);
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

.refresh-section {
  text-align: center;
  margin-top: 30rpx;
}

.refresh-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  
  &:disabled {
    opacity: 0.6;
  }
  
  &:not(:disabled):active {
    background: #5a6fd8;
  }
}
</style>